package com.easy.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alipay.api.AlipayApiException;
import com.easy.bean.*;
import com.easy.dao.CartDao;
import com.easy.dao.OrderDao;
import com.easy.dao.ProductDao;
import com.easy.dao.UserAddressDao;
import com.easy.service.IOrderService;
import com.easy.util.PaymentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    ProductDao productDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    UserAddressDao userAddressDao;
    @Autowired
    CartDao cartDao;

    @Transactional
    @Override
    public int addOrder(List<Integer> ids, List<Integer> numbers,Integer addressid, Integer uesrid) {
        //参数检查
        //1.两个集合中数据数量要一样
        //2.number中的数字不能小于1
        int idssize=-1;
        int numsize=-1;
        if(ids!=null&&numbers!=null) {
            idssize = ids.size();
            numsize = numbers.size();
            if (!(idssize > 0 && numsize > 0 && idssize == numsize)) {
                throw new RuntimeException("参数异常");
            }
        }
            else {
                throw new RuntimeException("参数异常");
            }
//        获取商品数据
        List<OrderInfo> orderInfoList=new ArrayList<>();
        BigDecimal total=new BigDecimal("0");
        int id=0;
        int number=0;
        for (int i = 0; i < ids.size(); i++) {
            id = ids.get(i);//商品id值
            number = numbers.get(i);//需要购买的数量
            Product pro = productDao.getProductByID(id);
            if (pro == null) {
                throw new RuntimeException("参数异常");
            }
            OrderInfo info = new OrderInfo();
            info.setImgurl(pro.getImgurl());
            info.setNumber(number);
            info.setPrice(pro.getPrice());
            info.setProductname(pro.getName());
            info.setProductid(pro.getId());
            orderInfoList.add(info);
            //计算总价格
            total = total.add(pro.getPrice().multiply(new BigDecimal(number)));
        }
            //封装订单
            Order order=new Order();
            order.setCode(IdUtil.fastUUID());
            order.setMoney(total);
            order.setUserid(uesrid);
            //保存  获取订单id(自增长)
            orderDao.addOrder(order);
            int orderid=order.getId();
            for (OrderInfo info:orderInfoList){
                info.setOrderid(orderid);
            }
            //封装订单明细
            orderDao.addOrderInfo(orderInfoList);
            //获取地址
            UserAddress userAddress=userAddressDao.getAddressByID(addressid);
            if (userAddress == null) {
                throw new RuntimeException("收货地址参数异常");
            }
            StringBuilder strB=new StringBuilder();
            strB.append(userAddress.getProvince());
            strB.append("-");
            strB.append(userAddress.getCity());
            strB.append("-");
            strB.append(userAddress.getArea());
            strB.append("-");
            strB.append(userAddress.getDetailed());
            String address=strB.toString();
            //处理地址
        OrderAddress orderAddress = new OrderAddress();
        orderAddress.setOrderid(orderid);
        orderAddress.setAddress(address);
        orderAddress.setName(userAddress.getAddressname());
        orderAddress.setTel(userAddress.getPhone());
        orderDao.addOrderAddress(orderAddress);

        for(Integer item:ids){
                Cart cart=new Cart();
                cart.setProductid(item);
                cart.setUserid(uesrid);
                cartDao.delete(cart);
            }
            return orderid;

        }




    @Override
    public String payment(Integer id) {
        Order order=orderDao.getOrderByID(id);
        if (order==null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getState() == -1) {
            throw new RuntimeException("订单已失效");
        }
        if (order.getState() !=0) {
            throw new RuntimeException("订单已支付");
        }
        //准备支付----生成二维码
        String url=null;
        try {
            url = PaymentUtil.Payment(order);
        } catch (Exception e) {
            throw new RuntimeException("支付服务异常");
        }
//        生成二维码图片
        BufferedImage img=QrCodeUtil.generate(url, 300, 300);
        //将图片转成base64的编码
        String qrcode = ImgUtil.toBase64(img, "png");
        return qrcode;

    }
    public int paymentSuccess(HashMap map){
        //检查订单是否存在 是否是阿里后台的回调
        String code=(String) map.get("code_trade_no");
        return orderDao.paymentSuccess(code);
    }

    @Override
    public Order getOrderByID(Integer id) {
        return orderDao.getOrderByID(id);
    }

    @Override
    public int cancelOrder() {
        return orderDao.cancelOrder();
    }

}
